﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

namespace PhuLeBussinessObject.Core
{
    public class CDataTable:DataTable
    {
        public CDataTable()
        {

        }
        public CDataTable(DataTable tbl)
        {
            this.Merge(tbl);
        }
        public string ToCSV(bool showColumnHeader = true)
        {
            string Separator = ";";

            //********* Header **********
            string csvHeader = "";
            for (int i = 0; i < this.Columns.Count; i++)
            {
                csvHeader += this.Columns[i].ColumnName + Separator;
            }

            if (csvHeader.EndsWith(Separator))
            {
                csvHeader = csvHeader.Remove(csvHeader.Length - 1);
            }
            //******** Data **********

            string template = "{0}" + Separator;
            string stringTemplate = "\"{0}\"" + Separator;
            StringBuilder sbData = new StringBuilder();
            for (int i = 0; i < Rows.Count; i++)
            {
                for (int j = 0; j < Columns.Count; j++)
                {
                    object obj = Rows[i][j];
                    if (obj == DBNull.Value)
                    {
                        sbData.Append(Separator);
                    }
                    else if (obj is DateTime)
                    {
                        sbData.AppendFormat(stringTemplate, ((DateTime)obj).ToString("yyyy-MM-dd HH:mm:ss.fff"));
                    }
                    else if (obj is string)
                    {
                        sbData.AppendFormat(template, Newtonsoft.Json.JsonConvert.SerializeObject(obj.ToString()));
                    }
                    else if (obj is byte[])
                    {
                        sbData.AppendFormat(template, System.Convert.ToBase64String((byte[])obj, 0, ((byte[])obj).Length));
                    }
                    else
                    {
                        sbData.AppendFormat(template, obj);
                    }
                }

                sbData.Append("\n");
                sbData.Replace(";\n", "\n");

            }
            
            string result =  sbData.ToString();
            if (showColumnHeader)
                result = csvHeader + "\n" + result;

            if (result.EndsWith("\n"))
                result = result.Remove(result.Length - 1);
            return result;
        }
    }
}
